import { baseUrl } from "./env";
import { apiUrl } from "./env";

export default async (url = "", data = {}, type = "GET", method = "fetch") => {
    type = type.toUpperCase();
    //url = baseUrl + url;
    url = apiUrl + url;
    console.log("apiUrl", apiUrl);
    //if (type == 'OPTIONS') { res.send(200); return }
    if (type == "GET") {
        let dataStr = ""; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + "=" + data[key] + "&";
        });

        if (dataStr !== "") {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));

            url = url + (url.indexOf("?") != -1 ? "&" : "?") + dataStr;
        }
        console.log(111, url, dataStr);
    }

    if (window.fetch && method == "fetch") {
        let requestConfig = {
            //credentials: 'include',
            method: type,
            headers: {
                // 'Accept': 'application/json',
                // dataType:'json',
                // 'Content-Type': 'application/json',  //
                // 'username':'0100',
                // 'token': '0100',
                "Content-Type":
                    "application/x-www-form-urlencoded; charset=UTF-8"
                // "Access-Control-Allow-Origin": "*"
                //'Access-Control-Allow-Headers':'Access-Control-Allow-Orgin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'
            },
            mode: "cors",
            cache: "force-cache"
        };
        console.log("data:", data);
        if (type == "POST") {
            console.log("data--post:", data);

            // Object.defineProperty(requestConfig, 'body', {
            // 	value:  JSON.stringify(data)
            // })
            var str = "",
                s = "";
            for (const key in data) {
                if (data.hasOwnProperty(key)) {
                    str += s + key + "=" + data[key];
                    s = "&";
                }
            }
            Object.defineProperty(requestConfig, "body", {
                value: str
            });
        }
        console.log("type", type);
        console.log("requestConfig", requestConfig);
        //alert('ddddd')
        /* 	if (type == 'OPTIONS') {  
			console.log('options')
			 return 200
		} */
        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            console.log("resonposJson:", responseJson);
            return responseJson;
        } catch (error) {
            throw new Error(error);
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject();
            }

            let sendData = "";
            if (type == "POST") {
                // sendData = JSON.stringify(data);
                sendData = data;
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader(
                "Content-type",
                "application/x-www-form-urlencoded"
            );
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response;
                        if (typeof obj !== "object") {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj);
                    } else {
                        reject(requestObj);
                    }
                }
            };
        });
    }
};
